#!/bin/sh
KUBE_CONFIG_DIR=/opt/kubeconfig
CONFIG_FILE_NAME=kubelet-bootstrap.kubeconfig
node_name=k8s-node03

export PATH=/opt/k8s/bin:$PATH

if [ ! -d ${KUBE_CONFIG_DIR} ]; then
    mkdir ${KUBE_CONFIG_DIR}
fi

export BOOTSTRAP_TOKEN=$(kubeadm token create \
      --description kubelet-bootstrap-token \
      --groups system:bootstrappers:${node_name} \
      --kubeconfig ~/.kube/config)


echo "Setting cluster..."
kubectl config set-cluster bootstrap \
  --certificate-authority=/opt/cert/ca.pem \
  --embed-certs=true \
  --server="https://##NODE_IP##:6443" \
  --kubeconfig=${KUBE_CONFIG_DIR}/${CONFIG_FILE_NAME}

echo "Setting credentials..."
kubectl config set-credentials kubelet-bootstrap \
  --token=${BOOTSTRAP_TOKEN} \
  --kubeconfig=${KUBE_CONFIG_DIR}/${CONFIG_FILE_NAME}

echo "setting context"
kubectl config set-context bootstrap \
  --cluster=bootstrap \
  --user=kubelet-bootstrap \
  --kubeconfig=${KUBE_CONFIG_DIR}/${CONFIG_FILE_NAME}

echo "Using context..."
kubectl config use-context bootstrap \
  --kubeconfig=${KUBE_CONFIG_DIR}/${CONFIG_FILE_NAME}

echo "replace variables with sed -e \"s/##NODE_NAME##/\${node_name}/\" kubelet.service.template > kubelet-\${node_name}.service"